package com.mdp.workflow.bus.listener.global;

import com.mdp.core.SpringUtils;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.micro.client.CallBizService;
import com.mdp.workflow.biz.ru.service.ProcinstNodeInfoService;
import com.mdp.workflow.cfg.FlowableListenerConfig;
import com.mdp.workflow.client.service.FlowMsgServiceImpl;
import com.mdp.workflow.comm.dict.ProcinstConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.impl.FlowableProcessCancelledEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 任务节点前置监听处理类
 * @author: Lu Yang
 * @create: 2019-05-04 20:51
 **/
@Component
public class ProcessCancelledListener implements FlowableEventListener {

	Log log=LogFactory.getLog(ProcessCancelledListener.class);

	@Value(value = "${mdp.form.data-approva-uri:/lcode/formData/processApprova}")
	String formDataApprovaUri="";

	@Autowired
	CallBizService callBizService;
	
	@Autowired
    FlowMsgServiceImpl pushMsgService;
	

	@Autowired
    ProcinstNodeInfoService procinstNodeInfoService;

    @Override
    public void onEvent(FlowableEvent event) {

    		log.debug("ProcessCompletedListener--->"+ event.getClass()+"______"+event.getType());
    		if(FlowableListenerConfig.PROCESS_CANCELLED.equals(event.getType().name())) {
    			//org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl
        		//org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl
            // 当前节点任务实体
        		  	String formId="";
        		  	//org.flowable.engine.delegate.event.impl.FlowableProcessCancelledEventImpl
        		  	FlowableProcessCancelledEventImpl exec=((FlowableProcessCancelledEventImpl) event); 
        			formId=(String) exec.getExecution().getVariable("formId");
		            
		            
		            //调用其它远程服务 
		            ExecutionEntityImpl exeEntity = (ExecutionEntityImpl)exec.getExecution(); 
		            //如果有上送restUrl，回调restUrl推送审核数据
		            String restUrl=(String) exeEntity.getVariable("restUrl");
		            String mainTitle=exeEntity.getName(); 
		            String taskName=exeEntity.getCurrentActivityName(); 
	                String startUserid=exeEntity.getStartUserId(); 
	                String commentMsg=(String) exeEntity.getVariable("commentMsg");
		            if(!StringUtils.isEmpty(restUrl)) {
		            	Map<String, Object> paramMap = new HashMap<String, Object>(); 
		                ///processInstance.get
		                String bizKey=exeEntity.getBusinessKey();
		                String processInstanceId=exeEntity.getProcessInstanceId();
		                Map<String,Object> flowVars=exeEntity.getVariables();
		                  
		                String actId=exeEntity.getCurrentActivityId(); 
		                String branchId=exeEntity.getTenantId();
		                String eventName=event.getType().name();
		                paramMap.putAll(flowVars);
		                paramMap.put("procInstId", processInstanceId);
		                paramMap.put("startUserid", startUserid);
		                paramMap.put("mainTitle", mainTitle);
		                paramMap.put("assignee", "");
		                paramMap.put("actId", actId);
		                paramMap.put("taskName", taskName);
		                paramMap.put("flowBranchId", branchId); 
		                paramMap.put("bizKey", bizKey);
		                paramMap.put("eventName", eventName); 
		                paramMap.put("commentMsg", commentMsg); 
		                paramMap.put("modelKey", exeEntity.getProcessDefinitionKey());
		                Tips tips = new Tips();
		                if(!StringUtils.isEmpty(formId)) {  
		                	paramMap.put("formId", formId);
		                	if(restUrl.indexOf(formDataApprovaUri)>=0) {
		                		tips=callBizService.postForTips(restUrl, paramMap);
		                	}else {
		                		tips=callBizService.postForTips(formDataApprovaUri, paramMap);
		                		tips=callBizService.postForTips(restUrl, paramMap);
		                	}
		                	
			            }else {
			            	tips=callBizService.postForTips(restUrl, paramMap);
			            } 
		            	if(tips.isOk()==false) {
		            		throw new BizException(tips);
		            	}
		            	
		            }
		            TaskService ts=SpringUtils.getBean(TaskService.class);
					String currentUsername=(String) exeEntity.getVariable(ProcinstConstants.CURR_USERNAME);
		            ts.addComment(null, exeEntity.getProcessInstanceId(), "流程已由"+currentUsername+"取消");
		            pushMsgService.pushMsg(startUserid, "您发起的流程【"+mainTitle+"】已被"+currentUsername+"取消");
		            procinstNodeInfoService.clearCacheNodeInfos(exeEntity.getProcessInstanceId());
    		}
    		

    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}